<template>
    <view class="container" :style="themeColor">
        <view class="box">
            <view class="logo">
                <image class="logo-img" v-show="logo" :src="logo ? easyGetImgUrl(logo) : '/static/logo.png'"></image>
                <text class="login-tip-text">您好，欢迎登录！</text>
            </view>
            <view class="login-box">
                <view class="card-group">
                    <view class="select-shop" @click="goSelectShop">
                        <image class="select-shop-icon" src="/static/icon/icon-login-select_shop.png"></image>
                        <text class="shop-name" :class="selectShop ? '' : 'shop-name-none'">{{
                            selectShop ? selectShop.Name : "请选择商户"
                        }}</text>
                        <uni-icons type="arrowright"></uni-icons>
                    </view>
                </view>
                <view class="card-group">
                    <card-cell-input :showLabel="false" ref="userName" label="/static/icon/icon_login_user.png"
                        :inputType="'number'" placeholder="请输入您的手机号"></card-cell-input>
                </view>
                <view class="card-group">
                    <card-cell-input v-if="isPwdType" :showLabel="false" ref="password"
                        label="/static/icon/icon_login_pwd.png" :inputType="'password'" placeholder="请输入登录密码">
                    </card-cell-input>
                    <view class="card-group-cell card-group-cell-code" v-else>
                        <image class="login-icon" src="/static/icon/icon_login_pwd.png"></image>
                        <input class="input" type="number" v-model="code" placeholder="请输入短信验证码"
                            placeholder-class="placeholderClass" />
                        <view class="btn-get-code">
                            <button class="btn" :disabled="disabled" @click="getCode"
                                :class="!disabled ? 'btn-success-hollow' : 'btn-fail-hollow'">
                                {{ countdown }}<text v-show="timestatus">秒重获</text>
                            </button>
                        </view>
                    </view>
                </view>
                <view class="link-box">
                    <text class="change-type" v-if="isSms && smsNO" @click="isPwdType = !isPwdType">{{
                        isPwdType ? "验证码登录" : "密码登录"
                    }}</text>
                    <text class="forget-pwd" v-if="isSms && isPwdType && smsNO"
                        @click="easyGoTo('/pages/login/reset')">忘记密码?</text>
                </view>
                <view class="agreement" v-if="getAppSet().agreement">
                    <label class="agrlabel" @click="selectFn(agreementchecked)">
                        <iconsfont customIcons="icon-yuanquan" :color="$store.state.themeColor" size="32"
                            v-show="!agreementchecked"></iconsfont>
                        <iconsfont customIcons="icon-xuanzhong1" :color="$store.state.themeColor" size="32"
                            v-show="agreementchecked"></iconsfont>
                    </label>
                    <view class="color-dark" @click="selectFn(agreementchecked)">登录注册表示您已阅读并同意</view>
                    <view><text @click="agreement()">《用户协议》</text>和<text @click="privacy()">《隐私政策》</text></view>
                </view>
                <button :disabled="checkCanLogin()" class="btn btn-success btn-save"
                    :class="checkCanLogin() ? 'disable' : ''" @click="loginByService">
                    登录
                </button>

                <view class="register-tip" v-if="canRegister" @click="goRegFn()">
                    <text>还没账号？点击</text><text class="link-text">注册</text>
                </view>
            </view>
        </view>

        <image class="loginBg" :src="easyGetImgUrl(loginBg)" v-if="loginBg" mode="aspectFill"></image>
        <!-- #ifdef MP -->
        <web-view class="webView" v-if="isShow" ref="webView" :src="url">
            <cover-view class="webView-mark" v-if="showNav"> </cover-view>
        </web-view>
        <!-- #endif -->
    </view>
</template>

<script>
import { mapMutations, mapState } from "vuex"
import cardCellInput from "@/components/common/cell/card-cell-input-login.vue"
import { getUserInfo, getProductDisplay, getInitWebInfo } from "@/utils/appInit.js"
import storage from "@/uni-sub-base/utils/storage.js"
import { getUserCarList } from "@/utils/cartUtil.js"
import config from "@/config/config.js"
import { UserLogin, QuickLogin, SendSmsNoVerifyCode, GetSms, GetLoginWay } from "@/service/api/member.js"

import webViewUrl from "@/pages/micro/webViewUrl.js"
import { getPlatform } from "@/uni-sub-base/utils/platformUtil.js"
export default {
    components: {
        cardCellInput,
    },
    data() {
        return {
            agreementchecked: false,
            isPwdType: true,
            logo: "",
            loginBg: "",
            isShow: false,
            url: "",
            showNav: false,
            selectShop: null,
            canRegister: false,
            isSms: false,
            smsNO: false,
            timestatus: false,
            disabled: false,
            code: "",
            countdown: "获取验证码",
            // 记录返回键被点击的次数
            backClickCount: 0,
            // 存储定时器
            timer: null
        }
    },
    onLoad(e) {
        setTimeout(() => {
            this.showNav = true
            this.$forceUpdate()
        }, 300)
    },
    mounted() {
        this.getsms()
        this.getloginWay()
    },
    onShow() {
        this.clearCache()
        this.getWebInfo()
    },
    onHide: function () {
        // 清除定时器
        clearTimeout(this.timer);
    },
    methods: {
        ...mapMutations(["SET_AUTH"]),
        selectFn(vaule) {
            this.agreementchecked = !this.agreementchecked
        },
        agreement() {
            // this.easyGoTo("/pages/web/h5?url=" + encodeURIComponent(this.getAppSet().agreementUrl))
            this.easyGoTo("/pages/web/agreement?type=4")
        },
        privacy() {
            // this.easyGoTo("/pages/web/h5?url=" + encodeURIComponent(this.getAppSet().privacyUrl))
            this.easyGoTo("/pages/web/agreement?type=5")
        },
        getsms() {
            GetSms().then((res) => {
                if (res.State == 1) {
                    this.isSms = true
                } else {
                    this.isSms = false
                }
            })
        },
        getloginWay() {
            GetLoginWay().then((res) => {
                if (res.State == 1) {
                    this.smsNO = true
                } else {
                    this.smsNO = false
                }
            })
        },
        getCode() {
            let userName = this.$refs.userName.getValue()
            var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
            var that = this
            if (userName == "") {
                this.easyToast("请输入手机号码")
                return false
            } else if (!myreg.test(userName)) {
                this.easyToast("请输入正确手机号码")
                return false
            } else {
                let path = "?tel=" + userName + "&validType=8"
                SendSmsNoVerifyCode(path)
                    .then((res) => {
                        that.disabled = true //禁用点击
                        if (res.State == 1) {
                            that.countdown = 60
                            that.timestatus = true
                            that.clear = setInterval(that.countDown, 1000)
                        } else {
                            this.easyToast(res.Msg)
                            that.disabled = false
                        }
                    })
                    .catch((err) => {
                        console.log(err)
                        that.disabled = false
                    })
            }
        },
        countDown() {
            var that = this
            if (!that.countdown) {
                that.disabled = false
                that.timestatus = false
                that.countdown = "获取验证码"
                clearInterval(that.clear)
            } else {
                --that.countdown
            }
        },
        loginByService() {
            if (!this.agreementchecked && this.getAppSet().agreement == true) {
                this.easyToast("请先同意《用户协议》和《隐私政策》")
                return
            }
            let userName = this.$refs.userName.getValue()
            this.showLoginLoadding()
            if (!this.code && this.isPwdType) {
                let password = this.$refs.password.getValue()
                let param = {
                    userName: userName,
                    password: password,
                }
                let path = "?userName=" + userName + "&password=" + password
                UserLogin(param).then((res) => {
                    if (res.State == 1) {
                        if (res.Data.State == 0) {
                            let token = res.Data.Token
                            this.goHome(token)
                        } else if (res.Data.State == 1) {
                            uni.hideLoading()
                            this.easyToast("您已提交注册申请，等待审核中")
                        } else {
                            uni.hideLoading()
                            this.easyToast(res.Data.StateName)
                        }
                    } else {
                        uni.hideLoading()
                        this.easyToast(res.Msg)
                    }
                })
            } else {
                if (this.code == "") {
                    this.easyToast("请输入验证码")
                    return false
                }
                let path = "?user_name=" + userName + "&valid_code=" + this.code + "&valid_type=8"
                QuickLogin(path).then((res) => {
                    if (res.State == 1) {
                        if (res.Data.State == 0) {
                            let token = res.Data.Token
                            this.goHome(token)
                        } else if (res.Data.State == 1) {
                            uni.hideLoading()
                            this.easyToast("您已提交注册申请，等待审核中")
                        } else {
                            uni.hideLoading()
                            this.easyToast(res.Data.StateName)
                        }
                    } else {
                        uni.hideLoading()
                        this.easyToast(res.Msg)
                    }
                })
            }

            // UserLogin(param).then(res=>{
            // 	if (res.State==1) {
            // 		if(res.Data.State==0){
            // 			//TODO Webapi UserLogin 这个接口token 进入h5 不识别
            // 			//目前先再引旧的接口
            // 			let param1 = {
            // 				password: password,
            // 				user_name: userName
            // 			}
            // 			mobileLogin(param1).then(res => {
            // 				if (res.status) {
            // 					let token = res.data.token
            // 					this.goHome(token)
            // 				}else {
            // 					uni.hideLoading()
            // 					this.easyToast(res.data)
            // 				}
            // 			})
            // 		}else if (res.Data.State==1){
            // 			uni.hideLoading()
            // 			this.easyToast("您已提交注册申请，等待审核中")
            // 		}else{
            // 			uni.hideLoading()
            // 			this.easyToast(res.Data.StateName)
            // 		}

            // 	}else {
            // 		uni.hideLoading()
            // 		this.easyToast(res.Msg)
            // 	}
            // })
        },
        goHome(token) {
            this.SET_AUTH(token)
            //#ifdef APP-PLUS
            if (getPlatform() == "ios") {
                let webInfo = storage.getCache("webInfo")
                if (webInfo) {
                    this.url =
                        webInfo.WebDomain +
                        (webInfo.AppHomeIndex ? webInfo.AppHomeIndex : webViewUrl.url.home) +
                        "?uniToken=" +
                        token
                }
                // this.isShow = true
                setTimeout((e) => {
                    this.getUserInfo()
                }, 2500)
                getUserCarList()
                getProductDisplay().then((res) => { })
            } else {
                this.getUserInfo()
                getUserCarList()
                getProductDisplay().then((res) => { })
            }
            //#endif
            //#ifndef APP-PLUS
            let webInfo = storage.getCache("webInfo")
            if (webInfo) {
                this.url =
                    webInfo.WebDomain +
                    (webInfo.AppHomeIndex ? webInfo.AppHomeIndex : webViewUrl.url.home) +
                    "?uniToken=" +
                    token
            }
            // this.isShow = true

            setTimeout((e) => {
                this.getUserInfo()
            }, 2500)
            getUserCarList()
            getProductDisplay().then((res) => { })
            //#endif
        },
        getUserInfo() {
            let url = "/pages/index/index"
            getUserInfo().then((res) => {
                uni.hideLoading()
                uni.reLaunch({
                    url: url,
                })
            })
        },
        saveUserInfo(data) {
            storage.setCache("userInfo", data)
        },

        showLoginLoadding() {
            uni.showLoading({
                title: "登录中",
            })
        },

        getWebInfo() {
            let webInfo = storage.getCache("webInfo")
            let selectShop = storage.getCache("selectShop")
            if (webInfo) {
                this.logo = webInfo.Logo
                this.loginBg = webInfo.LoginBackgroud
                this.canRegister = webInfo.AllowRegister
            }
            if (selectShop) {
                this.selectShop = selectShop
                getInitWebInfo(selectShop.MobileDomain, this)
                this.logo = selectShop.ShopLogo
                this.$forceUpdate()
            } else {
                setTimeout((e) => {
                    webInfo = storage.getCache("webInfo")
                    webInfo.Name = webInfo.BusinessName
                    this.selectShop = webInfo
                    this.$forceUpdate()
                }, 2000)
            }
        },
        disable() {
            if (this.$refs.userName && this.$refs.password) {
                let userName = this.$refs.userName.getValue()
                let password = this.$refs.password.getValue()
                return userName.trim() == "" || password.trim() == ""
            }
            return true
        },
        goSelectShop() {
            uni.navigateTo({
                url: "/pages/login/select-shop",
                events: {
                    getSelectData: (data) => {
                        if (data) {
                            this.selectShop = data
                            getInitWebInfo(data.MobileDomain, this)
                            storage.setCache("selectShop", data)
                            // setTimeout(e=>{
                            // 	this.getWebInfo()
                            // },500)
                        }
                    },
                },
            })
        },
        //设置主题色
        setThemeColorFn(Style) {
            //主题色
            let themeColor = ""
            switch (Style) {
                case "green":
                    themeColor = "#2cd334"
                    break
                case "blue":
                    themeColor = "#4076fc"
                    break
                case "purple":
                    themeColor = "#ff547c"
                    break
                case "black":
                    themeColor = "#000000"
                    break
                case "lightOrange":
                    themeColor = "#feae58"
                    break
                case "red":
                    themeColor = "#eb1010"
                    break
                case "rose":
                    themeColor = "#725abe"
                    break
                case "gyellow":
                    themeColor = "#dba868"
                    break
                case "orange":
                    themeColor = "#fe5822"
                    break
                case "blackBlue":
                    themeColor = "#2c4068"
                    break
                case "zise":
                    themeColor = "#fdbc00"
                    break
                case "style12":
                    themeColor = "#f6b7bc"
                    break
                case "style13":
                    themeColor = "#2a7472"
                    break
                case "weixing":
                    themeColor = "#0ab483"
                    break
                default:
                    themeColor = this.easyGetColor("main")
                    break
            }
            storage.setCache("themeColor", themeColor)
            this.SET_THEME_COLOR(themeColor)
        },
        checkCanLogin() {
            let can =
                (this.selectShop &&
                    this.$refs.userName &&
                    this.$refs.userName.getValue() != "" &&
                    this.$refs.password &&
                    this.$refs.password.getValue() != "") ||
                (this.selectShop &&
                    this.$refs.userName &&
                    this.$refs.userName.getValue() != "" &&
                    this.code &&
                    this.code != "")
            return !can
        },
        clearCache() {
            this.SET_AUTH("")
            storage.removeCache("token")
            storage.removeCache("userInfo")
            storage.removeCache("productDisplay")
        },
        goRegFn() {
            let url = "/pages/login/register?selectShopName=" + this.selectShop.Name
            this.easyGoTo(url)
        },
    },
    onBackPress(e) {
        var that = this
        if (e.from == "backbutton") {
            //#ifdef APP-PLUS
            // 第一次点击返回键，提示“再次点击退出”
            if (this.backClickCount === 0) {
                this.$toast('再次点击退出应用');
                this.backClickCount++;
                // 启动定时器，若用户不再点击，重置点击次数
                this.timer = setTimeout(() => {
                    this.backClickCount = 0;
                }, 2000); // 2秒内没有再次点击则重置
            } else {
                // 第二次点击，退出应用
                plus.runtime.quit();
            }
            // #endif
            return true
        }
    },
}
</script>

<style lang="scss">
page {
    background: #ffffff;
}

.container {
    padding: 0 80rpx;
}

.btn-save {
    margin-top: 50rpx;
    height: 88rpx;
    font-size: $font-size-36;
}

.logo {
    display: flex;
    padding-top: 150rpx;
    flex-direction: column;

    .logo-img {
        width: 140rpx;
        height: 140rpx;
        margin: 0 auto;
        margin-bottom: $app-page-padding;
        border-radius: 40rpx;
    }

    .login-tip-text {
        font-size: 40rpx;
        text-align: center;
        font-weight: bold;
        color: #333;
    }
}

.login-box {
    margin-top: 44rpx;

    .link-box {
        display: flex;
        flex-direction: row;
        height: 60rpx;
        justify-content: space-between;
        justify-items: center;

        .change-type {
            display: flex;

            color: $app-color-text-tip;
        }

        .forget-pwd {
            display: flex;

            justify-content: flex-end;
            color: $app-color-text-tip;
        }
    }

    .register-tip {
        margin-top: 30rpx;
        display: flex;
        justify-content: center;

        .link-text {
            color: $app-color-main;
        }
    }
}

.box {
    position: relative;
    z-index: 9;
}

.loginBg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    let: 0;
    right: 0;
    bottom: 0;
    z-index: 0;
}

.card-group {
    border-radius: 100rpx;
    background: #f5f6f7;
    margin-bottom: 40rpx;

    .card-group-cell {
        padding-top: 20rpx;
        padding-bottom: 20rpx;

        &:last-child {
            border-bottom: none;
        }
    }
}

.disable {
    opacity: 0.6;
    border: none;
    background: $app-color-main !important;
    color: #fff !important;
}

.webView-mark {
    width: 100vw;
    height: 100vh;
    background: #fff;
    position: fixed;
    z-index: 999999999999;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
}

.select-shop {
    min-height: 55rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: $app-page-padding $app-page-padding $app-page-padding 0;
    margin-left: $app-page-padding;
    border-bottom: solid 1rpx $uni-bg-color-grey;

    .select-shop-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: $app-page-padding;
    }

    .shop-name {
        color: $app-color-text-main;
        font-size: $font-size-36;
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .shop-name-none {
        font-size: $font-size-30;
        color: #bcbfcc;
    }
}

.card-group-cell {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: $app-page-padding $app-page-padding $app-page-padding 0;
    margin-left: $app-page-padding;
    border-bottom: solid 1rpx $uni-bg-color-grey;

    &:last-child {
        // border-bottom: 0;
    }

    .label {
        min-width: 180rpx;
    }

    .input {
        outline: none;
        border: none;
        width: 100%;
        display: flex;
        flex: 1;
        padding: 10rpx 0;
        font-size: $font-size-28;
    }

    .login-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: $app-page-padding;
    }

    .btn-get-code {
        display: flex;
        flex: 1;
        justify-content: flex-end;
    }
}

.card-group-cell-code {
    padding-top: 15rpx !important;
    padding-bottom: 15rpx !important;
}

.btn {
    margin-right: 0;
}

.btn-fail-hollow {
    color: #999;
    border: solid 1rpx #999;
}

.agreement {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 48rpx -60rpx -18rpx -60rpx;

    .circle {
        width: 28rpx;
        height: 28rpx;
        border-radius: 50%;
        border: 1rpx solid #999;
        display: block;
        overflow: hidden;
    }

    .agrlabel {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    view {
        font-size: 24rpx;

        text {
            color: $app-color-main !important;
        }
    }

    .color-dark {
        padding-left: 8rpx;
    }
}
</style>
